<?php

require_once 'model.php';

class netcontrol_dao
{
	protected $model = 'model';
	protected $db;
	
	public function __construct()
	{
		$this->db = db::get_instance();
	}
	
	public function fetch_contracts($day,$time)
	{
		$contracts = array();
		$day = strtolower($day);
		if ($day == 'saturday' || $day == 'sunday') {
			$week_part = 'weekend';
		} else {
			$week_part = 'workday';
		}
		$contracts_sql = '
			SELECT
				`contracts`.`handle`,
				`contracts`.`ip`,
				`contracts`.`mac`,
				`contracts`.`status`,
				`clients`.`username`,
				`clients`.`active`,
				`plans`.`iface`,
				`plans`.`download`,
				`plans`.`upload`,
				`plans`.`auth`,
				`plans`.`proxy_port`,
				`plans`.`router_depth`,
				COUNT(`schedules`.`day`) AS `scheduled`,
				`schedules`.`upload` AS `upload_sched`,
				`schedules`.`download` AS `download_sched`
			FROM `contracts`
			INNER JOIN `clients` ON (
				`contracts`.`client_id` = `clients`.`client_id` )
			INNER JOIN `plans` ON (
				`plans`.`plan_id` = `contracts`.`plan_id`)
			LEFT JOIN `schedules` ON (
				`schedules`.`plan_id` = `plans`.`plan_id` )
			WHERE ( `schedules`.`day` = "'.$day.'"
				OR `schedules`.`day` = "'.$week_part.'"
				OR `schedules`.`day` = "all" )
				AND `schedules`.`start` < "'.$time.'"
				AND `schedules`.`end` > "'.$time.'"
			GROUP BY `contracts`.`ip`';
		$contracts_result = $this->db->query($contracts_sql);
		for ($i=0; $contracts[$i] = $contracts_result->fetchObject($this->model); $i++) {}
		return $contracts;
	}

}

?>